/* eslint-disable prefer-promise-reject-errors */
import React, { useState, useRef, useEffect } from 'react';
import PropTypes from 'prop-types';
import Label from '../../../components/Label';
import Status from './Status';
import Loading from '@kuiper-components/loading';
import Input from '@knownsec/react-component/dist/Input';
import moment from 'moment'
import Select from '@knownsec/react-component/dist/Select';
import Button from '@knownsec/react-component/dist/Button';
import Dialog from '@knownsec/react-component/dist/Dialog';
import Icon from '@knownsec/react-component/dist/Icon';
import Message from '@knownsec/react-component/dist/Message';
import Breadcrumb, { Item } from '../../../components/Breadcrumb';
// import Dialog from '@kuiper-components/dialog';
import Form from '@knownsec/react-component/dist/Form';
import Tablev6 from './Tablev6';
import cn from 'classnames';
import s from './style.module.css';
import Helper from '../../../components/Helper';

import fetchFer from 'API/fetch';
import { withRouter } from 'react-router';
import notification from '@kuiper-components/notification';
const defaultFilter = {
	page: 1,
	limit: 10,
};
function Ipv6Monitor({ location }) {
	const prefilter = new URLSearchParams(location.search).get('filter');
	const isPlanTimeOut =
		moment().unix() > moment(sessionStorage.planTimeOut).unix();
	const filterS = prefilter ? JSON.parse(prefilter) || {} : {};
	const defaultFilter_ = { ...defaultFilter, ...filterS };
	const resD = JSON.parse(sessionStorage.resD);
	const balance = resD?.balance;
	const sispv6ManualTask = resD?.feature?.ipv6ManualTask;
	const [loading, setLoading] = useState(false);
	const [taskVisible, setTaskVisible] = useState(false);
	const [jobList, setJobList] = useState([]);
	const [lock, setLock] = useState(false);
	const [active, setActive] = useState(1);
	const [changeTable, setChangeTable] = useState(1);
	const [ipv6Num, setIpv6Num] = useState({
		total: balance.ipv6ManualTask?.total || 0,
		used: balance.ipv6ManualTask?.used || 0,
		ipv6ManualTask: sispv6ManualTask,
	});
	const form = useRef();
	const createIpv6 = async () => {
		window._hmt && window._hmt.push(['_trackEvent', 'IPv6', '新建任务']);
		if (isPlanTimeOut || !ipv6Num.ipv6ManualTask) {
			notification.error({
				message: '请先升级套餐服务',
				placement: 'top',
			});
			return;
		}
		if (ipv6Num?.total - ipv6Num?.used <= 0) {
			notification.error({
				message: '当前套餐检测数已达到上限，无法继续添加。',
				placement: 'top',
			});
			return;
		}
		const res = await fetchFer('/api/v2/users/balance/get', {
			method: 'GET',
		});
		sessionStorage.setItem('resD', JSON.stringify(res.results));
		const resD_ = res.results?.balance;
		const ipv6ManualTask_ = res.results?.feature?.ipv6ManualTask;
		setIpv6Num({
			total: resD_.ipv6ManualTask?.total || 0,
			used: resD_.ipv6ManualTask?.used || 0,
			ipv6ManualTask: ipv6ManualTask_,
		});
		setTaskVisible(true);
	};
	const submitValues = async e => {
		if (lock) {
			return false;
		}
		setLock(true);
		const formData = e || (await form.current.validateFields());
		if (!formData) {
			return false;
		}
		const res = await fetchFer(`/api/v2/jobs/ipv6/manual`, {
			method: 'POST',
			body: JSON.stringify(formData),
			checkStatus: 501,
		}).catch(error => {
			return error;
		});
		setLock(false);
		if (res.code === 200) {
			notification.success({
				placement: 'top',
				message: `${e ? '操作' : '添加'}成功`,
			});
			setChangeTable(Date.now());
			form.current.resetFields();
			setTaskVisible(false);
		} else {
			notification.error({
				message: `${e ? '操作' : '添加'}失败`,
				description: res.msg,
				placement: 'top',
			});
		}
	};
	const getAsset = async () => {
		const assetList = await fetchFer(`/api/v2/asset/verified-asset-ipv6`, {
			method: 'GET',
		});
		function unique(arr) {
			const res = new Map();
			return arr.filter(a => {
				return !res.has(a.targetUrl) && res.set(a.targetUrl, 1);
			});
		}
		const list = unique(assetList.results.JobMany).map(item => {
			return {
				label: item.note + '\t' + item.targetUrl,
				labelHtml: `<span style="width: 100px;display: inline-block;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;" title='${item.note}'>${item.note}</span>
 <span style="width: 200px;display: inline-block;margin-left: 10px;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;" title='${item.targetUrl}'>${item.targetUrl}</span>`,
				value: item.id,
			};
		});
		setJobList(list);
	};
	// 表单值绑定
	const onValues = (data, allValues) => {
		if (form.current) {
			form.current.setFieldsValue(
				Object.assign({}, form.current.getFieldValue(), data)
			);
		}
	};
	const statusChange = () => {
		setActive(Date.now());
	};
	const validatormap = (rule, value) => {
		if (rule.field === 'jobIds') {
			if (!value[0]) {
				return Promise.reject('资产地址不能为空');
			} else if (value.length > 100) {
				return Promise.reject('资产地址不超过100个');
			}
		}
		if (rule.field === 'name') {
			if (!value) {
				return Promise.reject('请输入任务名称');
			} else if (value.length > 50) {
				return Promise.reject('任务名称不超过50个字符');
			} else if (!(value.trim().replace(/[a-zA-Z0-9_\u4E00-\u9FA5]{1,50}/g, '').length === 0)) {
				return Promise.reject('名称格式错误，只能输入1～50个中文、英文字母、数字、下划线');
			}
		}
		return Promise.resolve();
	};
	useEffect(() => {
		getAsset();
	}, []);
	return (
		<div className={s.main}>
			<Breadcrumb>
				<Item disabled>任务管理</Item>
				<Item>IPv6合规检测</Item>
			</Breadcrumb>
			<div className={s.content}>
				<div className={s.cont}>
					<div className={cn(s.overview)}>
						<Label className={s.labelOverview}>
							<span>概况</span>
						</Label>
						<Loading show={loading}>
							<Status activeNum={active} />
						</Loading>
						<Label className={s.labelDetail}>任务列表</Label>
						<div className={cn(s.mt1r)}>
							<Button
								type="primary"
								onClick={
									isPlanTimeOut || !resD?.feature?.ipv6ManualTask
										? () => {
												return Message.show({
													type: 'error',
													message: '请先升级套餐服务',
												});
											}
										: createIpv6
								}
							>
								新建检测任务
							</Button>
						</div>
						<Tablev6
							searchData={defaultFilter_}
							changeTable={changeTable}
							onAgainTask={submitValues}
							statusChange={statusChange}
						/>
						<Dialog
							className={s.w500}
							title="新建检测任务"
							cancelText="取消"
							confirmText="下发任务"
							visible={taskVisible}
							onsubmit={submitValues}
							header={
								<div className={s.dialogHeader}>
									<span className={s.dialogTitle}>新建检测任务</span>
									<Icon
										type="cancel"
										onClick={() => {
											form.current.resetFields();
											setTaskVisible(false);
											setLock(false);
										}}
										className={cn(s.closeDialogBtn)}
									/>
								</div>
							}
							onhide={() => {
								form.current.resetFields();
								setTaskVisible(false);
								setLock(false);
							}}
						>
							<div className={cn(s.p20, s.pr)}>
								<Form
									ref={form}
									labelCol={{
										span: 6,
									}}
									wrapperCol={{
										span: 18,
									}}
									initialValues={{ name: '', jobIds: [] }}
									onValuesChange={(newItem, allValues) => {
										const val = recursion(newItem);
										function recursion(obj) {
											const obj_ = obj;
											const key = Object.keys(obj_);
											if (obj_[key] && typeof obj_[key] === 'object') {
												if ({}.propertyIsEnumerable.call(obj_[key], 'value')) {
													obj_[key] = obj_[key].value;
												} else if (
													{}.propertyIsEnumerable.call(obj_[key], 'selectedItem')
												) {
													if (obj_[key].selectedItem.length > 0) {
														if (obj_[key].selectedItem.length > 1) {
															obj_[key] = obj_[key].selectedItem.map(
																item => item.value
															);
														} else {
															obj_[key] = [obj_[key].selectedItem[0].value];
														}
													} else if (obj_[key].selectedItem.length === 0) {
														obj_[key] = [''];
													}
												} else {
													obj_[key] = recursion(obj_[key]);
												}
											}
											return obj_;
										}
										onValues(val, allValues);
									}}
								>
									<Form.Item
										label="任务名称"
										name="name"
										rules={[
											{
												required: true,
												validator: validatormap,
											},
										]}
									>
										<Input className={s.w300} placeholder="请输入任务名称" />
									</Form.Item>
									<Form.Item
										label="资产地址"
										name="jobIds"
										rules={[
											{
												required: true,
												validator: validatormap,
											},
										]}
									>
										<Select
											className={cn(s.w300, s.select)}
											placeholder="请选择资产地址"
											option={jobList}
											checkAll
											multiple
											searchable
											clearable
										/>
									</Form.Item>
									<div className={s.icons}>
										<Helper
											overlay="针对Web资产进行IPv6合规性检测"
											placement="top"
										/>
									</div>
									<div className={s.texts}>
										共计{ipv6Num.total}次，剩余
										<span className={s.maincolor}>
											{ipv6Num.total - ipv6Num.used}
										</span>
										次
									</div>
								</Form>
							</div>
						</Dialog>
					</div>
				</div>
			</div>
		</div>
	);
}
Ipv6Monitor.propTypes = {
	location: PropTypes.any,
};
export default withRouter(Ipv6Monitor);
